package com.zz.admin.auth.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zz.admin.auth.dto.DefaultUserDetails;
import com.zz.admin.auth.enums.BaseAuthExceptionEnum;
import com.zz.admin.auth.exception.CustomAccessDeniedException;
import com.zz.common.base.dto.ResponseDTO;
import com.zz.common.constants.ApiConstants;
import com.zz.common.constants.RedisKeyConstant;
import com.zz.common.utils.cache.RedisCacheUtils;
import com.zz.common.utils.common.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCacheUtils redisCacheUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Auth-Token");
        if (StringUtils.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        String userId;
        // 校验token
        try {
            ResponseDTO<Claims> responseDTO = TokenUtils.checkJWT(token);
            if (!responseDTO.getCode().equals(ApiConstants.RESULT_SUCCESS)) {
                throw new CustomAccessDeniedException(responseDTO.getCode(), responseDTO.getMessage());
            }
            userId = (String) responseDTO.getData().get("userId");
        } catch (Exception e) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(null, null));
            throw new CustomAccessDeniedException(((CustomAccessDeniedException) e).getCode() ,e.getMessage());
        }

        // 从redis中获取用户信息
        String redisKey = RedisKeyConstant.CURRENT_USER + userId;
        if (Objects.isNull(redisCacheUtils.getCacheObject(redisKey))) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(null, null));
            throw new AccessDeniedException(BaseAuthExceptionEnum.USER_NOT_LOGGED_IN.getMessage());
        }
        DefaultUserDetails userDetails = ((JSONObject) redisCacheUtils.getCacheObject(redisKey)).toJavaObject(DefaultUserDetails.class);
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
